"use client"

import { useRef, useState, useEffect } from "react"
import { ChevronDown } from "lucide-react"
import { Button } from "@/components/ui/button"
import { usePlayer } from "@/contexts/player-context"
import { useRouter } from "next/navigation"
import { LyricsView } from "@/components/lyrics/lyrics-view"
import Image from "next/image"

export default function NowPlayingPage() {
  const router = useRouter()
  const {
    state: { currentSong },
  } = usePlayer()
  const pageRef = useRef<HTMLDivElement>(null)
  const [isScrolling, setIsScrolling] = useState(false)
  const scrollTimeout = useRef<NodeJS.Timeout>()

  useEffect(() => {
    const handleScroll = () => {
      setIsScrolling(true)
      if (scrollTimeout.current) {
        clearTimeout(scrollTimeout.current)
      }
      scrollTimeout.current = setTimeout(() => {
        setIsScrolling(false)
      }, 2000)
    }

    const pageElement = pageRef.current
    if (pageElement) {
      pageElement.addEventListener("scroll", handleScroll)
    }

    return () => {
      if (pageElement) {
        pageElement.removeEventListener("scroll", handleScroll)
      }
      if (scrollTimeout.current) {
        clearTimeout(scrollTimeout.current)
      }
    }
  }, [])

  if (!currentSong) {
    router.push("/")
    return null
  }

  return (
    <div
      ref={pageRef}
      className="fixed inset-0 bg-gradient-to-b from-slate-800 to-slate-900 text-white overflow-y-auto"
    >
      <div className="min-h-screen flex flex-col">
        {/* Header */}
        <div className="px-4 py-6 flex items-center">
          <Button variant="ghost" size="icon" onClick={() => router.back()} className="text-white">
            <ChevronDown className="h-6 w-6" />
          </Button>
        </div>

        {/* Album Art */}
        <div className="relative w-64 h-64 mx-auto mt-4 mb-8">
          <Image
            src={currentSong.url || "/placeholder.svg"}
            alt={`${currentSong.title} cover`}
            width={256}
            height={256}
            objectFit="cover"
            className="rounded-lg shadow-lg"
          />
        </div>

        {/* Song Info */}
        <div className="px-6 mb-8 text-center">
          <h1 className="text-3xl font-bold mb-2">{currentSong.title}</h1>
          <h2 className="text-xl text-gray-300">{currentSong.artists}</h2>
        </div>

        {/* Lyrics */}
        <div className="flex-1">
          <LyricsView songId={currentSong.id} isUserScrolling={isScrolling} />
        </div>
      </div>
    </div>
  )
}

